﻿@{
    ViewData["Title"] = "角色管理";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"]</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" />
    <style>
        body { background: #f5f6fa; }
        .layui-card { max-width: 1200px; margin: 30px auto; }
    </style>
</head>
<body>
    <div class="layui-card">
        <div class="layui-card-header">
            <button class="layui-btn layui-btn-normal" onclick="addRole()">
                <i class="layui-icon">&#xe654;</i> 添加角色
            </button>
        </div>
        <div class="layui-card-body">
            <table id="roleTable" lay-filter="roleTable"></table>
        </div>
    </div>

    <!-- 表格操作列 -->
    <script type="text/html" id="tableBar">
        <div style="display: flex; justify-content: space-between; gap: 5px;">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assignPermission">分配权限</a>
        </div>
    </script>

    <!-- 添加/编辑角色弹窗 -->
    <div id="roleForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="roleForm">
            <input type="hidden" name="Id" />
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="RoleName" required lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="roleSubmit">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 分配权限弹窗 -->
    <div id="assignPermissionForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="assignPermissionForm">
            <input type="hidden" name="RoleId" />
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="RoleName" readonly class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">权限列表</label>
                <div class="layui-input-block" id="permissionTree" style="height: 320px; overflow-y: auto; border: 1px solid #e6e6e6; padding: 10px;"></div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="assignPermissionSubmit">保存</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <script src="~/libs/jquery/jquery.js"></script>
    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer', 'tree'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var tree = layui.tree;

            // 权限树实例
            var permissionTreeInst;
            // 当前选中的角色ID
            var currentRoleId;

            // 初始化表格
            table.render({
                elem: '#roleTable',
                url: '/RBAC/GetRole',
                page: true,
                request: {
                    pageName: 'page',  // 页码参数，和GetRole方法参数一致
                    limitName: 'limit' // 每页数量参数，和GetRole方法参数一致
                },
                cols: [[
                    { field: 'id', title: 'ID', width: 80, sort: true },
                    { field: 'roleName', title: '角色名称' },
                    { title: '操作', toolbar: '#tableBar', width: 300, align: 'center' }
                ]]
            });

            // 监听工具条
            table.on('tool(roleTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('确定删除此角色？', function (index) {
                        $.ajax({
                            url: '/RBAC/DelRole',
                            type: 'DELETE',
                            data: { id: data.id },
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('删除成功');
                                    obj.del();
                                } else {
                                    layer.msg('删除失败：' + res.message);
                                }
                            }
                        });
                        layer.close(index);
                    });
                } else if (obj.event === 'edit') {
                    editRole(data);
                } else if (obj.event === 'assignPermission') {
                    console.log('分配权限按钮被点击', data);
                    assignPermission(data);
                }
            });

            // 监听提交
            form.on('submit(roleSubmit)', function (data) {
                var isEdit = data.field.Id && Number(data.field.Id) > 0;
                var url = isEdit ? '/RBAC/UpRole' : '/RBAC/AddRole';
                var type = isEdit ? 'PUT' : 'POST';
                // 添加时不传Id字段
                if (!isEdit) {
                    delete data.field.Id;
                }
                $.ajax({
                    url: url,
                    type: type,
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    success: function (res) {
                        if (res.success) {
                            layer.closeAll();
                            layer.msg(isEdit ? '修改成功' : '添加成功');
                            table.reload('roleTable');
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
                return false;
            });

            // 分配权限
            function assignPermission(data) {
                currentRoleId = data.id;

                layer.open({
                    type: 1,
                    title: '分配权限',
                    area: ['600px', '580px'],
                    content: $('#assignPermissionForm'),
                    success: function() {
                        // 设置角色信息
                        layui.form.val('assignPermissionForm', {
                            RoleId: data.id,
                            RoleName: data.roleName
                        });

                        // 加载权限树
                        loadPermissionTree(data.id);
                    }
                });
            }

            // 加载权限树
            function loadPermissionTree(roleId) {
                // 先加载权限树
                $.ajax({
                    url: '/RolePermission/GetRolePermissionTree',
                    type: 'GET',
                    success: function(treeRes) {
                        if(treeRes.code === 0 && treeRes.data) {
                            // 转换数据格式以适配layui tree
                            var treeData = treeRes.data.map(function(item) {
                                return convertToTreeNode(item);
                            });

                            // 获取角色已有权限
                            $.ajax({
                                url: '/RolePermission/GetRolePermissionByRoleId',
                                type: 'GET',
                                data: { roleId: roleId },
                                success: function(permRes) {
                                    console.log('获取角色权限结果:', permRes);
                                    var checkedIds = [];

                                    if(permRes.success && permRes.data && permRes.data.permissionIds) {
                                        // 直接使用返回的权限ID列表
                                        checkedIds = permRes.data.permissionIds;
                                        console.log('从permissionIds中获取的权限:', checkedIds);
                                    }

                                    console.log('需要选中的ID列表:', checkedIds);

                                    // 渲染树并选中已有权限
                                    permissionTreeInst = tree.render({
                                        elem: '#permissionTree',
                                        data: treeData,
                                        showCheckbox: true,
                                        id: 'permissionTreeId',
                                        accordion: false
                                    });

                                    // 设置选中状态
                                    if(checkedIds && checkedIds.length > 0) {
                                        console.log('开始设置选中状态');
                                        checkedIds.forEach(function(id) {
                                            console.log('设置选中节点:', id);
                                            tree.setChecked('permissionTreeId', id);
                                        });
                                    } else {
                                        console.log('没有选中的权限ID');
                                    }
                                },
                                error: function(err) {
                                    console.error('获取角色权限失败:', err);
                                    layer.msg('获取角色权限失败');
                                }
                            });
                        } else {
                            layer.msg('获取权限树失败');
                        }
                    },
                    error: function() {
                        layer.msg('获取权限树失败');
                    }
                });
            }

            // 递归转换树节点格式
            function convertToTreeNode(node) {
                var treeNode = {
                    id: node.id,
                    title: node.label,
                    spread: false
                };

                if(node.children && node.children.length > 0) {
                    treeNode.children = node.children.map(function(child) {
                        return convertToTreeNode(child);
                    });
                }

                return treeNode;
            }

            // 监听分配权限表单提交
            form.on('submit(assignPermissionSubmit)', function(data) {
                // 获取选中的权限ID
                var checkedData = tree.getChecked('permissionTreeId');
                var permissionIds = [];

                // 递归获取所有选中节点ID
                function getCheckedIds(data) {
                    data.forEach(function(item) {
                        permissionIds.push(item.id);
                        if(item.children && item.children.length > 0) {
                            getCheckedIds(item.children);
                        }
                    });
                }

                getCheckedIds(checkedData);

                // 构造请求数据
                var requestData = {
                    RoleId: parseInt(data.field.RoleId),
                    PermissionId: permissionIds
                };

                // 发送请求
                $.ajax({
                    url: '/RolePermission/AddRolePermission',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function(res) {
                        if(res.success) {
                            layer.closeAll();
                            layer.msg('权限分配成功');
                        } else {
                            layer.msg('权限分配失败: ' + (res.message || '未知错误'));
                        }
                    },
                    error: function() {
                        layer.msg('权限分配请求失败');
                    }
                });

                return false;
            });
        });

        // 添加角色
        function addRole() {
            layer.open({
                type: 1,
                title: '添加角色',
                area: ['500px', '400px'],
                content: $('#roleForm'),
                success: function () {
                    layui.form.val('roleForm', {
                        Id: null,
                        RoleName: '',
                    });
                }
            });
        }

        // 编辑角色
        function editRole(data) {
            layer.open({
                type: 1,
                title: '编辑角色',
                area: ['500px', '400px'],
                content: $('#roleForm'),
                success: function () {
                    layui.form.val('roleForm', {
                        Id: data.id,
                        RoleName: data.roleName,
                    });
                }
            });
        }
    </script>
</body>
</html>